package me.pinion.controller;


import me.pinion.check.annotation.AllowRole;
import me.pinion.controller.annotation.RouteBind;
import me.pinion.model.book.Book;
import me.pinion.model.book.Chapter;
import me.pinion.model.User;
import me.pinion.service.ChapterService;
import me.pinion.service.CommentService;

import javax.servlet.http.HttpServletResponse;

@RouteBind("/chapter")
public class ChapterController extends Controller{

    ChapterService chapterService;
    CommentService commentService;

    public void index(){
        if (getPara(0) != null){
            this._detail(getParaToInt(0));
            return;
        }
        render("/book/chapter_detail.ftl");
    }

    private void _detail(int id){
        Chapter chapter = Chapter.dao.findById(id);
        setAttr("chapter", chapter);
        render("/book/chapter_detail.ftl");
    }


    @AllowRole({"USER"})
    public void create(){
        Book book = Book.dao.findById(getParaToInt(0));
        setAttr("book", book);
        if ("POST".equals(getRequest().getMethod())){
            Chapter chapter = chapterService.create(getPara("title"), getPara("text"), book);
            book.getChapters().add(Chapter.dao.findById(chapter.getId()));
            renderJson(chapter);
        }else {
            render("/book/chapter_create.ftl");
        }
    }

    @AllowRole({"USER"})
    public void edit(){
        Chapter chapter = Chapter.dao.findById(getParaToInt(0));
        if (!chapter.getBook().isAuthor(this.<User>getSessionAttr("user"))){
            renderError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        setAttr("chapter", chapter);
        if ("POST".equals(getRequest().getMethod())){
            chapterService.update(chapter, getPara("title"), getPara("text"));
        }
        render("/book/chapter_edit.ftl");
    }

    public void delete(){
        int id = getParaToInt("id");
        Chapter chapter = Chapter.dao.findById(id);
        if (chapter.getBook().isAuthor(curUser())){
            chapter.set("enabled", false);
            chapter.update();
            renderJson(chapter);
        }else {
            renderError(HttpServletResponse.SC_FORBIDDEN);
        }

    }
}
